#![no_std]
#![no_main]
#![feature(alloc_error_handler)]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#![feature(maybe_uninit_ref)]
#![feature(type_alias_impl_trait)]
extern crate alloc;

mod common;

use common::hal::{clocks, gpio, rng::Rng};
use common::peripheral::take_peripherals;
use common::thread;
use cortex_m_rt::entry;
use embassy::util::Forever;
use embassy_nrf::{gpiote, interrupt, uarte};
use embedded_hal::digital::v2::{InputPin, OutputPin};
use futures_util::stream::StreamExt;
use task_stream::TaskStream;

static RNG: Forever<Rng> = Forever::new();
static LED1: Forever<gpio::Pin<gpio::Output<gpio::PushPull>>> = Forever::new();

fn get_random(buf: &mut [u8]) -> Result<(), getrandom::Error> {
    let rng: &mut Rng = unsafe { RNG.steal() };
    rng.random(buf);
    return Ok(());
}

#[thread::task]
async fn btn_task(ch: gpiote::InputChannel<gpiote::Ch0, gpio::PullUp>) {
    let mut status = false;
    loop {
        ch.wait().await;
        thread::sleep_ms(20).await;
        if ch.pin().is_high().unwrap() {
            //松开
        }
    }
}

#[thread::task]
async fn tick() {
    loop {
        task_stream::tick(100);
        thread::sleep_ms(100).await;
    }
}
#[thread::task]
async fn executor() {
    let mut stream = TaskStream::stream();
    while let Some(task) = stream.next().await {
        task.run();
    }
}

#[thread::task]
async fn heart() {
    loop {
        thread::sleep_ms(30_000).await;
    }
}

#[entry]
fn main() -> ! {
    let (sdp, p) = take_peripherals();
    common::init_alloc();
    /*----- sys clock -----*/
    clocks::Clocks::new(sdp.CLOCK)
        .disable_ext_hfosc()
        .set_lfclk_src_rc()
        .start_lfclk();
    /*----- bsp start -----*/
    let port0 = gpio::p0::Parts::new(p.P0);
    let pins = uarte::Pins {
        rxd: port0.p0_14.into_floating_input().degrade(),
        txd: port0
            .p0_18
            .into_push_pull_output(gpio::Level::Low)
            .degrade(),
        cts: None,
        rts: None,
    };
    let uart = unsafe {
        uarte::Uarte::new(
            p.UARTE0,
            interrupt::take!(UARTE0_UART0),
            pins,
            uarte::Parity::EXCLUDED,
            uarte::Baudrate::BAUD115200,
        )
    };
    let (exti, chs) = gpiote::Gpiote::new(p.GPIOTE, interrupt::take!(GPIOTE));
    let btn = port0.p0_29.into_pullup_input().degrade();
    let ch = gpiote::InputChannel::new(exti, chs.ch0, btn, gpiote::InputChannelPolarity::Toggle);
    let led1 = port0
        .p0_31
        .into_push_pull_output(gpio::Level::High)
        .degrade();
    LED1.put(led1);
    /*----- bsp end  -----*/
    let rng = Rng::new(sdp.RNG);
    RNG.put(rng);
    getrandom::register_custom_getrandom!(get_random);

    thread::start(p.RTC1, |spawner| {
        let _err = spawner.spawn(btn_task(ch));
        let _err = spawner.spawn(tick());
        let _err = spawner.spawn(executor());

    });
}
